package yanjun.tool.validate.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.ReflectionUtils;
import yanjun.tool.validate.proxy.CGLibValidateProxy;
import yanjun.tool.validate.proxy.ValidateProxy;
import yanjun.tool.validate.util.ReflectUtils;

import javax.validation.Valid;
import javax.validation.Validator;
import java.lang.reflect.Method;


public class ValidateBeanPostProcessor implements  BeanPostProcessor {

    private Validator validator;

    public ValidateBeanPostProcessor(Validator validator)
    {
        this.validator=validator;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(ReflectUtils.hasAnnotation(bean.getClass(), Valid.class))
        {
            Method[] methods = bean.getClass().getMethods();
            for(Method method:methods)
            {
               if(ReflectUtils.hasAnnotationArgument(method,Valid.class))
               {
                   ValidateProxy validateProxy=new CGLibValidateProxy(validator);
                   return validateProxy.generateProxy(bean);
               }
            }
        }
        return bean;
    }
}
